﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Singer.Core
{
    public static class Tools
    {
        private static readonly RandomNumberGenerator NumberGenerator = RandomNumberGenerator.Create();

        /// <summary>
        /// MD5加密 32位小写
        /// </summary>
        public static string MD5(string text)
        {
            MD5 mD = System.Security.Cryptography.MD5.Create();
            byte[] bytes = Encoding.UTF8.GetBytes(text);
            byte[] array = mD.ComputeHash(bytes);
            StringBuilder stringBuilder = new StringBuilder();
            byte[] array2 = array;
            foreach (byte b in array2)
            {
                stringBuilder.Append(b.ToString("x2"));
            }
            return stringBuilder.ToString().ToLower();
        }

        /// <summary>
        /// 生成有序的GUID
        /// </summary>
        /// <returns></returns>
        public static string BuildSequentialGuid()
        {
            var randomBytes = new byte[10];
            NumberGenerator.GetBytes(randomBytes);
            long timestamp = DateTime.UtcNow.Ticks / 10000L;

            // Then get the bytes
            byte[] timestampBytes = BitConverter.GetBytes(timestamp);

            // Since we're converting from an Int64, we have to reverse on
            // little-endian systems.
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(timestampBytes);
            }

            byte[] guidBytes = new byte[16];

            Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);
            Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10);

            // If formatting as a string, we have to compensate for the fact
            // that .NET regards the Data1 and Data2 block as an Int32 and an Int16,
            // respectively.  That means that it switches the order on little-endian
            // systems.  So again, we have to reverse.
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(guidBytes, 0, 4);
                Array.Reverse(guidBytes, 4, 2);
            }
            var guid = new Guid(guidBytes).ToString("N");
            Console.WriteLine(guid);
            return guid;
        }
    }
}
